package com.softstao.guoyu.ui.activity.shop;

import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.softstao.guoyu.R;
import com.softstao.guoyu.base.BaseActivity;
import com.softstao.guoyu.global.GsonManager;
import com.softstao.guoyu.global.SharePreferenceManager;
import com.softstao.guoyu.model.shop.CartGoods;
import com.softstao.guoyu.model.shop.CartList;
import com.softstao.guoyu.model.shop.OrderProductInfo;
import com.softstao.guoyu.mvp.interactor.shop.CartInteractor;
import com.softstao.guoyu.mvp.presenter.shop.CartPresenter;
import com.softstao.guoyu.mvp.viewer.shop.CartListViewer;
import com.softstao.guoyu.ui.activity.MainActivity;
import com.softstao.guoyu.ui.adapter.CartAdapter;
import com.softstao.softstaolibrary.library.utils.LZUtils;
import com.softstao.softstaolibrary.library.widget.FullyLinearLayoutManager;
import com.softstao.softstaolibrary.library.widget.LZToast;
import com.wangjie.androidinject.annotation.annotations.mvp.AIPresenter;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by vaikus on 2017/7/10.
 */

public class CartActivity extends BaseActivity implements CartListViewer,CartAdapter.CartListener{

    @AIPresenter(presenter = CartPresenter.class,interactor = CartInteractor.class)
    CartPresenter presenter;

    @BindView(R.id.checkbox)
    CheckBox checkbox;
    @BindView(R.id.total_price_view)
    TextView totalPriceView;
    @BindView(R.id.cart_list)
    RecyclerView listView;
    @BindView(R.id.empty_layout)
    LinearLayout emptyLayout;
    @BindView(R.id.loading)
    RelativeLayout loading;
    private List<CartGoods> cartGoodsList = new ArrayList<>();
    private List<CartGoods> checkedGoods = new ArrayList<>();
    private List<OrderProductInfo> orderProductInfos = new ArrayList<>();
    private CartAdapter adapter;
    private Float allPrice = new Float(0);
    private CartList cartList;

    @Override
    public int _ContentView() {
        return R.layout.activity_cart;
    }

    @Override
    public void initView() {
        initTitle("购物车");

        adapter = new CartAdapter(cartGoodsList);
        adapter.setCartListener(this);
        listView.setAdapter(adapter);
        listView.setLayoutManager(new FullyLinearLayoutManager(this));

        checkbox.setOnCheckedChangeListener((buttonView, isChecked) -> {
             /*
                 * 判断一：（全选按钮选中）全选按钮是否选择，如果选择，那么列表每一行都选中
				 * 判断二：（全选按钮取消）当取消全选按钮时，会有两种情况
				 * ，第一：主动点击全选按钮，此时直接取消列表所有的选中状态，第二：取消列表某一行，导致全选取消，此时列表其他行仍然是选中
				 *
				 * 判断二的分析：（主动取消）判断列表每一行的选中状态，如果全部都是选中状态，那么（列表选中数=列表总数），此时属于主动取消，
				 * 则取消所有行的选中状态，反之（被动取消）则不响应
				 */

            // 记录列表每一行的选中状态数量
            int isChoice_all = 0;
            if (isChecked) {
                // 设置全选
                for (int i = 0; i < cartGoodsList.size(); i++) {
                    // 如果选中了全选，那么就将列表的每一行都选中
                    if(listView.getChildAt(i)!=null){
                        ((CheckBox) (listView.getChildAt(i)).findViewById(R.id.checkbox)).setChecked(true);
                    }
                }
            } else {
                // 设置全部取消
                for (int i = 0; i < cartGoodsList.size(); i++) {
                    // 判断列表每一行是否处于选中状态，如果处于选中状态，则计数+1
                    if(listView.getChildAt(i)!=null){
                        if (((CheckBox) (listView.getChildAt(i)).findViewById(R.id.checkbox)).isChecked()) {
                            // 计算出列表选中状态的数量
                            isChoice_all += 1;
                        }
                    }
                }
                // 判断列表选中数是否等于列表的总数，如果等于，那么就需要执行全部取消操作
                if (isChoice_all == cartGoodsList.size()) {
                    // 如果没有选中了全选，那么就将列表的每一行都不选
                    for (int i = 0; i < cartGoodsList.size(); i++) {
                        // 列表每一行都取消\
                        if(listView.getChildAt(i)!=null) {
                            ((CheckBox) (listView.getChildAt(i)).findViewById(R.id.checkbox)).setChecked(false);
                        }
                    }
                }
            }
            setTotalPrice();
        });
    }

    public void setTotalPrice(){
        BigDecimal bd = new BigDecimal(allPrice);
        Float p = bd.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
        totalPriceView.setText(getResources().getString(R.string.rmb) + LZUtils.priceFormat(p));
    }

    @OnClick({R.id.confirm_btn, R.id.buy_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.confirm_btn:
                if (checkedGoods.size()>0){
                    startActivity(new Intent(context,OrderConfirmActivity.class).putExtra("goods", (Serializable) checkedGoods));
                    checkedGoods.clear();
                    adapter.notifyDataSetChanged();
                }else {
                    LZToast.getInstance(context).showToast("请选择商品结算！");
                }
                break;
            case R.id.buy_btn:
                startActivity(new Intent(context, MainActivity.class).putExtra("index","0"));
                finish();
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        findCartList();
    }

    private void update(){
        orderProductInfos.clear();
        for (int i=0;i<cartGoodsList.size();i++){
            OrderProductInfo orderProductInfo = new OrderProductInfo();
            orderProductInfo.setProductId(cartGoodsList.get(i).getProductId());
            orderProductInfo.setCount(cartGoodsList.get(i).getNum());
            orderProductInfos.add(orderProductInfo);
        }
    }

    @Override
    public void findCartList() {
        presenter.getCartList(SharePreferenceManager.getInstance().getAgentId());
    }

    @Override
    public void updateCartList() {
        presenter.updateCartList(SharePreferenceManager.getInstance().getAgentId(), GsonManager.getInstance().getGson().toJson(orderProductInfos));
    }

    @Override
    public void getCartList(CartList cartList) {
        if (cartList == null || cartList.getProductList() == null || cartList.getProductList().size() == 0) {
            emptyLayout.setVisibility(View.VISIBLE);
            return;
        }
        this.cartList = cartList;
        cartGoodsList.clear();
        cartGoodsList.addAll(cartList.getProductList());
        adapter.notifyDataSetChanged();
        emptyLayout.setVisibility(View.GONE);
    }

    @Override
    public void updateResult(CartList cartList) {
        if (cartList == null || cartList.getProductList() == null || cartList.getProductList().size() == 0) {
            emptyLayout.setVisibility(View.VISIBLE);
            return;
        }
        this.cartList = cartList;
        cartGoodsList.clear();
        cartGoodsList.addAll(cartList.getProductList());
        adapter.notifyDataSetChanged();
        emptyLayout.setVisibility(View.GONE);
    }

    @Override
    public void getChoiceData(int position, boolean isChoice) {
        if (cartGoodsList.get(position).getPrice()!=0) {
            if (isChoice) {
                allPrice += cartGoodsList.get(position).getSubtotal();
                checkedGoods.add(cartGoodsList.get(position));
            } else {
                allPrice -= cartGoodsList.get(position).getSubtotal();
                checkedGoods.remove(cartGoodsList.get(position));
            }
            setTotalPrice();
        }
        // 记录列表处于选中状态的数量
        int num_choice = 0;
        for (int i = 0; i < cartGoodsList.size(); i++) {
            // 判断列表中每一行的选中状态，如果是选中，计数加1
            if (null != listView.getChildAt(i) && ((CheckBox) (listView.getChildAt(i)).findViewById(R.id.checkbox)).isChecked()) {
                // 列表处于选中状态的数量+1
                num_choice += 1;
//                is_choice[i] = true;
            }
        }
        // 判断列表中的CheckBox是否全部选择
        if (num_choice == cartGoodsList.size()) {
            // 如果选中的状态数量=列表的总数量，那么就将全选设置为选中
            checkbox.setChecked(true);
        } else {
            // 如果选中的状态数量！=列表的总数量，那么就将全选设置为取消
            checkbox.setChecked(false);
        }
    }

    @Override
    public void subtractPrice(int position, boolean isChecked, int preNumber, int number) {
        update();
        if (cartGoodsList.get(position).getNum()-cartGoodsList.get(position).getBoxNum()==0){
            if (isChecked) {
                allPrice -= cartGoodsList.get(position).getPrice() * cartGoodsList.get(position).getBoxNum();
                setTotalPrice();
            }
            orderProductInfos.remove(position);
            cartGoodsList.remove(position);
            adapter.notifyItemRemoved(position);
        }else {
            orderProductInfos.get(position).setCount(cartGoodsList.get(position).getNum() - cartGoodsList.get(position).getBoxNum());
            if (isChecked) {
                allPrice -= cartGoodsList.get(position).getPrice() * cartGoodsList.get(position).getBoxNum();
                setTotalPrice();
            }
        }
        updateCartList();
    }

    @Override
    public void addPrice(int position, boolean isChecked) {
        update();
        orderProductInfos.get(position).setCount(cartGoodsList.get(position).getNum()+cartGoodsList.get(position).getBoxNum());
        if (isChecked) {
            allPrice += cartGoodsList.get(position).getPrice() * cartGoodsList.get(position).getBoxNum();
            setTotalPrice();
        }
        updateCartList();
    }

    @Override
    public void del(int position) {
        update();
        orderProductInfos.remove(position);
        cartGoodsList.remove(position);
        adapter.notifyItemRemoved(position);
        updateCartList();
    }
}
